package com.kun.video.ui.dialog;

import com.kun.video.AbstractApplication;
import com.kun.video.util.CssManager;
import javafx.scene.control.ButtonType;
import javafx.scene.control.DialogPane;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.stage.Modality;
import javafx.stage.Window;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * TODO
 *
 * @author gzc
 * @since 2025/3/15 3:02
 **/
public class ExceptionDialog extends AbstractDialog<Boolean> {

    private TextArea textArea;
    private Label errMsgLabel;

    public ExceptionDialog(Throwable throwable) {
        this(throwable, AbstractApplication.getAppStage());
    }

    public ExceptionDialog(Throwable throwable, Window owner) {
        super("错误提示", "", owner, Modality.APPLICATION_MODAL);
        // 异常信息转字符串
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        throwable.printStackTrace(pw);
        textArea.setText(sw.toString());
        this.errMsgLabel.setText("错误原因 : " + throwable.getMessage());
        DialogPane dialogPane = getDialogPane();
        dialogPane.getButtonTypes().clear();
        dialogPane.getButtonTypes().add(ButtonType.OK);
        dialogPane.setMinSize(600, 400);
        dialogPane.setPrefSize(600, 400);
        dialogPane.setMaxSize(600, 400);
    }

    @Override
    protected Region createCenter() {
        textArea = new TextArea("");
        CssManager.getInstance().disableFocusedBorderStyle(textArea);
        errMsgLabel = new Label();
        errMsgLabel.setStyle("-fx-font-size: 18px;-fx-padding: 5px");
        // 构建错误提示框
        Label label = new Label("详细异常信息如下：");
        label.setStyle("-fx-font-size: 13px;-fx-padding: 3px");
        // 是否可编辑
        textArea.setEditable(false);
        // 是否换行
//        textArea.setWrapText(true);
        textArea.setMaxWidth(Double.MAX_VALUE);
        textArea.setMaxHeight(Double.MAX_VALUE);
        GridPane.setVgrow(textArea, Priority.ALWAYS);
        GridPane.setHgrow(textArea, Priority.ALWAYS);
        GridPane expContent = new GridPane();
        expContent.setStyle("-fx-padding: 5px");
        expContent.setMaxWidth(Double.MAX_VALUE);
        expContent.add(errMsgLabel, 0, 0);
        expContent.add(label, 0, 1);
        expContent.add(textArea, 0, 2);
        return expContent;
    }

    @Override
    protected Boolean convertResult(ButtonType buttonType) {
        return buttonType == ButtonType.OK;
    }

}
